package com.github.tetrisgame.ui.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.text.SpannableStringBuilder;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.github.tetrisgame.R;
import com.github.tetrisgame.utils.UIUtils;

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class AgreementView extends View {
    private SpannableStringBuilder text = new SpannableStringBuilder();
    private float textSize = UIUtils.sp2px(20);
    private int maxLines = 2;
    private String dots = "...";
    private Paint mTextPaint = new Paint();
    private int textColor = Color.parseColor("#0F3460");
    private int mWidth = 0;
    private int textCount = 0;
    private int linesCount = 0;
    private float floatLinesCount = 0;
    private ArrayList<String> list = new ArrayList<>();
    private float OneWidth = 0;
    private boolean isExceed = false;
    private int[] stringLengthGroups;
    private int[] colorGroups;
    private int padding = UIUtils.dp2px(15);
    public AgreementView(Context context) {
        this(context,null);
    }

    public AgreementView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs,0);
    }

    public AgreementView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.AgreementView);
        setMaxLines(typedArray.getInteger(R.styleable.AgreementView_maxLines1,0));
    }
    private void init(){
        text.append("<span color=\"#F5F5F5\">还是不来烦你</span><span color=\"#000000\">北京房子那边发你真的不能发啊热结果哦一哈啦啦</span>");

// 修正后的正则表达式：捕获颜色值和文本内容
        Pattern pattern = Pattern.compile("<span color=\\\"#([0-9A-Fa-f]{6})\\\">([^<]+)</span>");
        Matcher matcher = pattern.matcher(text.toString());

// 先计算匹配次数
        int matchCount = 0;
        while (matcher.find()) {
            matchCount++;
        }
        matcher.reset(); // 重置matcher以便重新遍历

// 初始化数组
        colorGroups = new int[matchCount];
        stringLengthGroups = new int[matchCount];

        int i = 0;
        SpannableStringBuilder textAux = new SpannableStringBuilder();
        while (matcher.find()) {
            // 提取颜色值并去掉引号
            String colorHex = "#" + matcher.group(1); // 正则中已排除#，这里手动添加
            colorGroups[i] = Color.parseColor(colorHex);

            // 提取文本内容并计算长度
            String content = matcher.group(2);
            textAux.append(content);
            stringLengthGroups[i] = content.length();

            i++;
        }
        text = textAux;

        mTextPaint.setColor(Color.BLACK);
        mTextPaint.setTextSize(textSize);
        mTextPaint.setTextAlign(Paint.Align.LEFT);
        mTextPaint.setColor(textColor);


    }

    @Override
    protected void onDraw(@NonNull Canvas canvas) {
        drawTextString(canvas);
    }

    private void drawTextString(Canvas canvas) {
        int colorCount = 0;
        int totalCount = 0;

        Paint.FontMetrics fontMetrics = mTextPaint.getFontMetrics();
        float dy = fontMetrics.bottom - fontMetrics.top;
        String lastTextString = list.get(maxLines - 1);
        int x = 0;
        for (int i = 0; i < maxLines - 1; i++) {
            char[] chars = list.get(i).toCharArray();
            for (int j = 0; j < chars.length; j++) {
                mTextPaint.setColor(colorGroups[colorCount]);
                if (stringLengthGroups[colorCount] > 0){
                    stringLengthGroups[colorCount]--;
                }else{
                    colorCount++;
                }
                canvas.drawText(String.valueOf(chars[j]),x,-fontMetrics.top + i * dy,mTextPaint);
                x += (int) mTextPaint.measureText(String.valueOf(chars[j]));
            }
            x = 0;
        }
        if(maxLines < list.size()){
            for (int i = lastTextString.length() - 2; i > 0; i--) {
                if(mTextPaint.measureText(lastTextString.subSequence(0,i-1).toString()) + mTextPaint.measureText("...") <= getWidth()){
                    lastTextString = lastTextString.subSequence(0,i-1) + "...";
                    break;
                }
            }
        }
        x = 0;
        char[] chars = lastTextString.toCharArray();
        for (int j = 0; j < chars.length; j++) {
            mTextPaint.setColor(colorGroups[colorCount]);
            if (stringLengthGroups[colorCount] > 0){
                stringLengthGroups[colorCount]--;
            }else{
                colorCount++;
            }
            canvas.drawText(String.valueOf(chars[j]),x,-fontMetrics.top + maxLines * dy,mTextPaint);
            x += (int) mTextPaint.measureText(String.valueOf(chars[j]));
        }


    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mWidth = getWidth();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        Paint.FontMetrics fontMetrics = mTextPaint.getFontMetrics();
        int realWidth = 0;
        int desire = (int)mTextPaint.measureText(text.toString());
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        if(widthMode == MeasureSpec.EXACTLY){
            realWidth = widthSize;
        }else{
            if(desire > widthSize){
                realWidth = widthSize;
            }else{
                realWidth = desire;
            }
        }
        int realHeight;
        list = new ArrayList<>();
        int start = 0;
        int line = 0;
        for (int i = 0; i < text.length(); i++) {
            String listString = text.subSequence(start,i).toString();
            if(mTextPaint.measureText(listString) > realWidth){
                list.add(text.subSequence(start,i-1).toString());
                start = i - 1;
                line++;
            }

        }
        if(start < text.length()){
            line++;
            list.add(text.subSequence(start,text.length()).toString());
        }
        if(maxLines > 0){
            if(maxLines > line)maxLines = line;
            realHeight = maxLines * (int)(fontMetrics.bottom - fontMetrics.top);
        }else{
            maxLines = line;
            realHeight = maxLines * (int)(fontMetrics.bottom - fontMetrics.top);
        }

        realHeight = resolveSizeAndState(realHeight,heightMeasureSpec,MEASURED_STATE_TOO_SMALL);
        setMeasuredDimension(realWidth,realHeight);

    }

    public void setText(String text) {
        this.text.clear();
        this.text.append(text);
    }
    public void setTextSize(float textSize) {
        this.textSize = textSize;
    }

    public void setMaxLines(int maxLines) {
        this.maxLines = maxLines;
        invalidate();
    }
}
